﻿#include "home.h"
#include "ui_home.h"
#include<QFile>
#include<QMessageBox>
#include<QSqlQuery>
#include<QPainter>

extern int gAccount;
home::home(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::home)
{
    ui->setupUi(this);
    setWindowFlag(Qt::FramelessWindowHint);
    loadStyleSheet();
    initControl();
}

QPixmap home::getRoundImg(const QPixmap &src,QPixmap &mask, QSize maskSize)
{
    if (maskSize == QSize(0, 0)) {
            maskSize = mask.size();
        }
        else {
            mask = mask.scaled(maskSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        }
        QImage resultImage(maskSize, QImage::Format_ARGB32_Premultiplied);
        QPainter painter(&resultImage);
        painter.setCompositionMode(QPainter::CompositionMode_Source);
        painter.fillRect(resultImage.rect(), Qt::transparent);
        painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
        painter.drawPixmap(0, 0, mask);
        painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
        painter.drawPixmap(0, 0, src.scaled(maskSize,Qt::KeepAspectRatio, Qt::SmoothTransformation));
        painter.end();
        return QPixmap::fromImage(resultImage);
}

home::~home()
{
    delete ui;
}

void home::loadStyleSheet()
{
    QFile file(":/src/QSS/home.css");
    if(file.open(QFile::ReadOnly)){
        QString str=file.readAll();
        setStyleSheet(str);
        file.close();
    }else{
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("加载样式表失败!"));
    }
}

void home::initControl()
{
    QSqlQuery query(QString("select username,picture from info where account=%1").arg(gAccount));
    query.first();
    ui->nameLabel->setText(query.value(0).toString());
    QPixmap mask;
    mask.load(":/src/img/head_mask.png");
    ui->headLabel->setPixmap(getRoundImg(QPixmap(query.value(1).toString()),
                                         mask,ui->headLabel->size()));
    m_contact=new contact;
}

void home::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton){
        m_point=event->globalPos()-mapToGlobal(QPoint(0,0));
        event->accept();
    }
}

void home::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton){
        move(event->globalPos()-m_point);
        event->accept();
    }
}

void home::on_closeBtn_clicked()
{
    close();
    delete m_contact;
}

void home::on_chatBtn_clicked()
{
    m_contact->show();
}
